﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace _00_DllCall
{
    class Program
    {
        public delegate int MessageBoxMethod(IntPtr hWnd, [MarshalAs(UnmanagedType.LPWStr), In] string text, [MarshalAs(UnmanagedType.LPWStr), In] string caption, int type);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr LoadLibrary(string fileName);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private static extern bool FreeLibrary(IntPtr hModule);

        [DllImport("kernel32.dll", CharSet = CharSet.Ansi)]
        private static extern MessageBoxMethod GetProcAddress(IntPtr hModule, string lpProcName);

        static void Main(string[] args)
        {
            IntPtr hModule = LoadLibrary("User32.dll");
            if (hModule != IntPtr.Zero)
            {
                try
                {
                    string procName = "MessageBoxW";
                    MessageBoxMethod method = GetProcAddress(hModule, procName);
                    int result = method(IntPtr.Zero, "12345", "abcd", 0);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
                finally
                {
                    FreeLibrary(hModule);
                }//try
            }//if
        }
    }

}
